// import Taro from '@tarojs/taro'
import Api, { Response } from '@/src/lib/api/api'
import AddressModel from '@/src/lib/models/address_model'

export interface AddressState {
    [x: string]: any
    
    addressList: AddressModel[],
    lastUseAddress: AddressModel
}

export default {
    namespace: "address",
    state: {},
    reducers: {
        setState(state, { payload }) {
            return {...state, ...payload}
        },

        setLastUseAddress(state, { payload }) {
            return { ...state, ...{ lastUseAddress: payload } }
        }
    },
    effects: {
        
        /**
         * 获取收货地址列表
         */
        *getAddressList({}, { put, call }) {
            let res: Response = yield call(Api.userGoodsAddressList)
            if (!Api.handleResponse(res)) {
                return null
            }

            yield put({
                type: "setState", 
                payload: {
                    addressList: res.data.goodsaddress
                }
            })

            return res.data.goodsaddress
        },

        /**
         * 新增/编辑收货地址
         */
        *editAddress({ payload }, { put, call }) {
            let res: Response
            if (payload.id) {
                res = yield call(Api.userGoodsAddressEdit, payload)
            } else {
                res = yield call(Api.userGoodsAddressAdd, payload)
            }
            if (!Api.handleResponse(res)) {
                return null
            }

            yield put({
                type: "getAddressList"
            })

            return res.data
        },

        *deleteAddress({ payload }, { put, call }) {
            let res: Response = yield call(Api.userGoodsAddressDel, payload)
            if (!Api.handleResponse(res)) {
                return false
            }
            
            yield put({
                type: "getAddressList"
            })
            return true
        }
    }
}